<template>
	<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="40rpx 40rpx 0 0" :is-mask-click="false">
		<view class="flex flex-col items-center mt-60">
			<image style="width: 180rpx;height: 180rpx;" src="/static/user-login.svg"></image>
		</view>
		<view class="flex flex-col items-center px-36">
			<view>小依陪伴</view>
			<view class="label mt-20">AI让陪伴相随</view>
			<view class="xiaoyi-disabled-btn w-full mt-60" v-if="!isOk" @tap="isOkHandle">开始使用</view>
			<button v-else open-type="getPhoneNumber" class="xiaoyi-btn w-full mt-60"
				@getphonenumber="getPhoneNumber">开始使用</button>
			<view class="flex items-center label" style="transform: scale(0.7);margin: 20rpx 30rpx 50rpx">
				<checkbox-group @change="isOk = !isOk">
					<checkbox color="#6F47FF" style="margin-right: 30rpx" :value="isOk" :checked="false" />
				</checkbox-group>
				<view style="transform: scale(1.1);">我已阅读并知悉《小依陪伴隐私协议》</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	export default {
		name: "user-login-popup",
		data() {
			return {
				isOk: false
			};
		},
		methods: {
			open() {
				uni.getStorage({
					key: 'openid',
					success: () => {
						this.getUserInfo()
					},
					fail: () => {
						this.$refs.popup.open();
					}
				})
			},
			isOkHandle() {
				if (!this.isOk) {
					uni.showToast({
						icon: 'error',
						title: '请勾选阅读隐私协议'
					})
					return;
				}
			},
			getUserInfo() {
				uni.request({
					method: "get",
					url: '/api/v1/user/info/getInfo',
					success: (res) => {
						if(res.data.code === 0){
							getApp().globalData.userInfo = res.data?.data;
						}
					}
				})
			},
			getPhoneNumber(phone) {
				if (phone?.detail?.code) {
					uni.showLoading({
						title: '正在登录...'
					});
					uni.login({
						provider: "weixin",
						onlyAuthorize: true,
						success: (event) => {
							uni.request({
								method: "POST",
								url: '/api/v1/auth/miniLogin',
								data: {
									code: event.code
								},
								success: ({
									data
								}) => {
									if (data.code === 0) {
										uni.setStorageSync('openid', data.data.openid)
										uni.request({
											method: "post",
											url: '/api/v1/user/info/getPhone',
											data: {
												code: phone.detail.code
											},
											success: ({
												data
											}) => {
												if (data.code === 0) {
													this.getUserInfo();
													this.$refs.popup.close();
												}
											},
											complete: () => {
												uni.hideLoading();
											}
										})
									} else {
										uni.hideLoading();
									}
								}
							});
						},
						fail: () => {
							uni.hideLoading();
						}
					});
				}
			}
		}
	}
</script>

<style>

</style>